package club.zhilin.guli.service.edu.listener;

import club.zhilin.guli.service.edu.domain.Subject;
import club.zhilin.guli.service.edu.domain.dto.SubjectDTO;
import club.zhilin.guli.service.edu.mapper.SubjectMapper;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhilin
 * @since 2022/1/22 22:31
 */
@Slf4j
@NoArgsConstructor
@AllArgsConstructor
public class ExcelSubjectListener extends AnalysisEventListener<SubjectDTO> {

    private SubjectMapper subjectMapper;

    /**
     * 遍历每一行数据
     *
     * @param subjectDTO      课程类别传输对象
     * @param analysisContext 监听器上下文
     */
    @Override
    public void invoke(SubjectDTO subjectDTO, AnalysisContext analysisContext) {
        log.info("解析到一条记录:{}", subjectDTO);
        Subject subject = this.getByTitle(subjectDTO.getLevelOneCategory());
        String parentId;
        if (subject == null) {
            Subject parent = new Subject();
            parent.setTitle(subjectDTO.getLevelOneCategory());
            parent.setParentId("0");
            this.subjectMapper.insert(parent);
            parentId = parent.getId();
        } else {
            parentId = subject.getId();
        }
        Subject sub = this.getSubByTitle(subjectDTO.getLevelTwoCategory(), parentId);
        if (sub == null) {
            Subject children = new Subject();
            children.setTitle(subjectDTO.getLevelTwoCategory());
            children.setParentId(parentId);
            this.subjectMapper.insert(children);
        }
    }

    /**
     * 最后的收尾工作
     *
     * @param analysisContext 监听器上下文
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("收尾工作");
    }

    /**
     * 根据title查找父节点
     *
     * @param title title
     * @return subject对象
     */
    private Subject getByTitle(String title) {
        return subjectMapper.selectOne(new LambdaQueryWrapper<Subject>().eq(Subject::getTitle, title).eq(Subject::getParentId, "0"));
    }

    /**
     * 根据父级id和子级标题查询对象
     *
     * @param title    子级标题
     * @param parentId 父级id
     * @return subject对象
     */
    private Subject getSubByTitle(String title, String parentId) {
        return subjectMapper.selectOne(new LambdaQueryWrapper<Subject>().eq(Subject::getTitle, title).eq(Subject::getParentId, parentId));
    }
}
